/**
 * @class 2DUI排序
 * @author DuskyHuang 圣子
 * @description 此处排序方法参考大佬nomat文章，论坛原帖：https://forum.cocos.org/t/topic/145371
*/


import { _decorator, Component, CCInteger, Enum, UITransform } from 'cc';
import { serialize, tip } from '../../utils';
import '../../utils/cc/batch';
const { ccclass, property, disallowMultiple, requireComponent, executeInEditMode } = _decorator;

enum SortingLayer {

    LAYER_BACK_MOST = -99,

    UI_3D_BACK = -6,
    UI_3D_MID = -5,
    UI_3D_FRONT = -4,

    EFFECT_3D_BACK = -3,
    EFFECT_3D_MID = -2,
    EFFECT_3D_FRONT = -1,

    LAYER_DEFAULT = 0,

    LAYER_BASE_BACK = 1,
    LAYER_BASE_MID = 2,
    LAYER_BASE_FRONT = 3,

    LAYER_POPS_BACK = 4,
    LAYER_POPS_MID = 5,
    LAYER_POPS_FRONT = 6,

    LAYER_INFO_BACK = 7,
    LAYER_INFO_MID = 8,
    LAYER_INFO_FRONT = 9,

    LAYER_FRONT_MOST = 99,
}

const ORDER_IN_LAYER_MAX = 1000;

function sortingEnabled(this: SortingGroup): boolean { return this.sortingEnabled; }

@ccclass('cfw.SortingGroup')
@requireComponent(UITransform)
@disallowMultiple(true)
@executeInEditMode(true)
export class SortingGroup extends Component {

    public static readonly SortingLayer: typeof SortingLayer = SortingLayer;
    public static readonly ORDER_IN_LAYER_MAX: num.posInt = ORDER_IN_LAYER_MAX;

    @tip('排序层', sortingEnabled, ['type', Enum(SortingLayer)])
    public get sortingLayer(): SortingLayer { return this._sortingLayer; }
    public set sortingLayer(arg: SortingLayer) { this._sortingLayer = arg; this._upload(); }

    @tip('层内序', sortingEnabled, ['type', CCInteger], [0, ORDER_IN_LAYER_MAX, 1])
    public get orderInLayer() { return this._orderInLayer; }
    public set orderInLayer(arg: number) { this._orderInLayer = arg; this._upload(); }

    @property
    public get sortingEnabled(): boolean { return this._sortingEnabled; }
    public set sortingEnabled(arg: boolean) { this._sortingEnabled = arg; this._uit.sortingEnabled = arg; }

    protected onLoad(): void { this._uit = this.getComponent(UITransform); }

    protected onEnable(): void { this._upload(); }

    protected onDisable(): void { this._clear(); }

    private _upload(): void {
        const sign = this._sortingLayer < 0 ? -1 : 1;
        this._uit.sortingPriority = sign * (Math.abs(this._sortingLayer) * ORDER_IN_LAYER_MAX + this._orderInLayer);
        this._uit.sortingEnabled = this._sortingEnabled;
    }

    private _clear(): void { this._uit.sortingPriority = 0; }

    private _uit: UITransform = null;
    @serialize private _orderInLayer: number = 0;
    @serialize private _sortingEnabled: boolean = false;
    @serialize private _sortingLayer: SortingLayer = SortingLayer.LAYER_DEFAULT;
}